import {View, Text, StyleSheet, Image, TextInput, TouchableOpacity, AlertButton, ScrollView} from 'react-native'
import React, {Component} from 'react'
import {AppIcon} from "../../assets/icon/AppIcon";
import {padding, default as styles, margin, HUNDRED_PERCENT} from "../../style";
import Icon from 'react-native-vector-icons/MaterialCommunityIcons';
import {AlertButtonStyle, alertProxy, AlertProxyBtn} from "../../component/common/AlertProxy";
import {Actions} from "react-native-router-flux";
import {inject, observer} from "mobx-react/custom";
import {Store} from "../../store";
import {toFixed} from "../../util";
import toast from "../../component/common/ToastProxy";

interface WithDrawProps extends Store {

}

interface WithDrawState {
    outScore: number,
    showAmountTip: boolean,
    canWithDrawn: boolean,
}

@inject("withDraw", "user", "income")
@observer
export default class WithDraw extends Component<WithDrawProps, WithDrawState> {
    state = {
        outScore: 0,
        showAmountTip: false,
        canWithDrawn: false,
        textValue: 0
    };
    withDrawComp: TextInput;

    constructor(props: WithDrawProps) {
        super(props);
        this.props.withDraw.getStoreInfo();
    }

    async componentDidMount() {
        const canWithDrawn = await this.props.withDraw.checkWithDrawnAuthority();
        this.setState({
            canWithDrawn
        })
    }

    fees() {
        const {storeInfo} = this.props.withDraw;
        return (storeInfo.fees || 0) * 0.01
    }

    feesScore() {
        return +toFixed(this.fees() * this.state.outScore, 0)
    }

    depositRatio() {
        const {storeInfo} = this.props.withDraw;
        return (storeInfo.depositRatio || 0) * 0.01
    }

    depositScore() {
        return +toFixed(this.state.outScore * this.depositRatio(), 0)
    }

    updateOutScore = (text: string) => {
        const {withDrawnIntegral} = this.props.user.user;
        const value = +text || 0;
        const outScore = value > withDrawnIntegral ? withDrawnIntegral : value;
        const showAmountTip = outScore % 100 !== 0;
        this.setState({
            outScore, showAmountTip
        })
    };
    withDrawnHandle = async () => {

        if (this.state.outScore <= 0) {
            toast("提现金额不能为零！");
            return;
        }
        if (!this.state.canWithDrawn) {
            toast("一周只能提现一次，您本周已提现！");

            return;
        }
        if (this.state.showAmountTip) {
            toast("提现只能是100的整数倍,\r\n并且不能超过可提现金额~");

            return;
        }
        const isSuccess = await this.props.withDraw.sendWithDrawnRequest({
            outScore: +this.state.outScore,
            feesScore: +this.feesScore(),
            depositScore: +this.depositScore(),
        });
        if (isSuccess) {
            toast("提现申请提交成功,需1-2个工作日到账！");
            //    刷新用户信息
            this.props.user.refreshUserData();
            //     更新我的收益页面的数据
            this.props.income.getIncomeProfileByUserId();
        } else {
            toast("提现申请失败,不满足以下条件:\r\n" +
                "1. 提现只能是整数倍\r\n" +
                "2. 一周只能提现一次\r\n" +
                "3. 提现金额不能为零")
        }
        setTimeout(_ => {
            Actions.pop();
        }, 1000)
    };

    actuallyOutPoints() {
        return toFixed(this.state.outScore - this.feesScore() - this.depositScore(), 2);
    }

    _renderContent() {
        const {withDrawnIntegral} = this.props.user.user;


        return (<View>
            {/*onPress={() => alertProxy(null, "请添加银行卡", alertBtns)}*/}
            <TouchableOpacity style={[WithDrawStyle.rowStyle]}>
                <View style={[WithDrawStyle.rowStyle, {paddingHorizontal: 0}]}>
                    <AppIcon name={"wangyin"} color={"#ccc"} size={33}/>
                    <View style={{marginHorizontal: 20}}>
                        <Text style={WithDrawStyle.boldFont}>银行账户</Text>
                        {/*<Text style={[WithDrawStyle.middleFont, {marginTop: 5}]}>6222****2444</Text>*/}
                    </View>
                </View>
                <AppIcon name={"youjiantou"} color={"#ccc"} size={14}/>
            </TouchableOpacity>
            <View style={[WithDrawStyle.rowStyle]}>
                <Text style={WithDrawStyle.labelFont}>可提现积分</Text>
                <Text style={WithDrawStyle.bigBoldFont}>{withDrawnIntegral}</Text>
            </View>
            <View style={[WithDrawStyle.rowStyle]}>
                <Text style={WithDrawStyle.labelFont}>本次提现</Text>
                <TextInput onChangeText={this.updateOutScore} autoCorrect={true} autoCapitalize={"none"}
                           underlineColorAndroid={"transparent"}
                           placeholderTextColor={"#D6D6D6"}
                           keyboardType={"number-pad"}
                           placeholder={"请输入提现金额"}
                           style={[WithDrawStyle.bigBoldFont, styles.flex, {
                               textAlign: "right",
                               marginLeft: 50
                           }, padding(0)]}/>
            </View>
        </View>)
    }

    _renderTips() {
        return (<View style={[{marginTop: 12}, styles.centerH]}>
            <Icon name={"lightbulb-on"} size={22} color={"#FF7C02"}/>
            <Text numberOfLines={2} style={[WithDrawStyle.tipsFont, margin(7, 53)]}>
                本次提现预留{this.depositRatio() * 100}%，即{this.depositScore()}分，可用于商城非指定商品消费，手续费{this.fees() * 100}%即{this.feesScore()}分，实际到账{this.actuallyOutPoints()}。
            </Text>
            {this.state.showAmountTip ?
                <Text style={{color: "red", marginTop: 20, textAlign: "center"}}>注意: 提现金额只能为100的倍数~</Text> : null}
        </View>)
    }

    render() {
        return (<ScrollView bounces={false} contentContainerStyle={{flex: 1}}>
            {this._renderContent()}
            {this._renderTips()}
            <TouchableOpacity
                onPress={this.withDrawnHandle}
                style={[styles.centered, {
                    marginHorizontal: 14,
                    paddingVertical: 12,
                    backgroundColor: "#629C36",
                    borderRadius: 30,
                    marginTop: 20
                }]}>
                <Text style={WithDrawStyle.btnFont}>提现</Text>
            </TouchableOpacity>
            <Text style={WithDrawStyle.underTips}>注：提现正常需1-2个工作日到账</Text>
        </ScrollView>)
    }
}

const WithDrawStyle = StyleSheet.create({
    container: {},
    rowStyle: {
        flexDirection: "row",
        alignItems: "center",
        justifyContent: "space-between",
        backgroundColor: "#fff",
        marginTop: 1,
        paddingHorizontal: 20,
        height: 60
    },
    boldFont: {
        fontWeight: "bold",
        color: "#333",
        fontSize: 14
    },
    middleFont: {
        color: "#666",
        fontSize: 12
    },
    labelFont: {
        color: "#333",
        fontSize: 14
    },
    bigBoldFont: {
        fontWeight: "bold",
        color: "#333",
        fontSize: 16
    },
    tipsFont: {
        fontSize: 12,
        color: "#FF7C02",
        lineHeight: 17,
        textAlign: "center"
    },
    btnFont: {
        fontSize: 14,
        color: "#fff"
    },
    underTips: {
        textAlign: "center",
        marginTop: 77,
        color: "#999",
        fontSize: 12
    }
});

 